using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
using Newtonsoft.Json;
using System.Collections;
using Stormwind.Core.Contracts;

namespace Stormwind.Business.Rules {
	/// <summary>
	/// Class responsible for managing users.
	/// </summary>
	public class UserManager {

		/// <summary>
		/// Gets all users as Xml.
		/// </summary>
		/// <param name="currentItem">Current page.</param>
		/// <param name="pageSize">Page size.</param>
		/// <returns>Returns Xml as string.</returns>
		[AjaxPro.AjaxMethod]
		public static string GetAllUsers(int currentItem, int pageSize) {
			try {
				int pageIndex = Convert.ToInt32(Math.Ceiling((decimal)(currentItem + 1) / pageSize)) - 1;
				int totalRecords = 0;
				MembershipUserCollection muc = Membership.GetAllUsers(pageIndex, pageSize, out totalRecords);

				List<User> users = new List<User>();
				foreach (MembershipUser user in muc) {
					users.Add(new User(user));
				}
				StringWriter sw = new StringWriter();
				XmlTextWriter xw = new XmlTextWriter(sw);
				XmlSerializer xs = new XmlSerializer(typeof(List<User>));
				xs.Serialize(xw, users);

				string xml = sw.ToString();
				xml = xml.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", string.Empty).Replace(@"<ArrayOfUser xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">", string.Empty).Replace("</ArrayOfUser>", string.Empty);
				return @"<Users xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" totalCount=""" + totalRecords.ToString() + "\">" + xml + "</Users>";
			}
			catch (System.Exception ex) {
				throw ex;
			}
		}
	}
}
